package cn.jn.lhm.part07;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author lhm 2753914576@qq.com
 * @time 2024/10/17 - 下午9:30
 **/
public class Acceptor extends ServerThread {

    private final ServerSocketChannel serverSocketChannel;

    private final Server server;

    private final List<PollerIO> ioThreads;

    private int cursor = 0;

    public Acceptor(String name, Server server, Set<PollerIO> pollerIOSet) throws IOException {
        super(name);
        this.server = server;
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.bind(new InetSocketAddress(server.getPort()));
        // 注册
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);

        // 不可变的IO线程集合
        this.ioThreads = List.copyOf(pollerIOSet);
    }


    @Override
    public void run() {
        // socket not close & not stop
        while (!server.isStopped() && !serverSocketChannel.socket().isClosed()) {
            try {
                this.selector.select();
                Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // 获取连接
                        doAccept(key);
                    }
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        closeSelector();
    }

    private void doAccept(SelectionKey key) throws IOException {
        SocketChannel socketChannel = this.serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        if (cursor >= ioThreads.size()) {
            cursor = 0;
        }
        // socketChannel bind poller
        ioThreads.get(cursor++).bind(socketChannel);
    }
}
